require 'config/boot'
require 'config/environment'
require 'set'
require 'csv'

dir_path = ENV['dir']
task :register_examples => [:register_gogi_in_example] do
  Dir::glob(File.expand_path(dir_path)+'/**/*.csv').each do |source_file|
    CSV.foreach(source_file) do |line|
      if line.at(0).match(Regexp.new('^\d*$')).blank?
        next if line[1..-3].all?{|item| item.blank? }
        targets = line.at(0).split(Regexp.new('\s'))
        @midashi = DirectionWord.find(:all,:include => :acceptations, :conditions => ["direction_words.text IN (#{['?'] * targets.size * ','})"] + targets )
        @gogi = @midashi.map{|item| item.acceptations }.flatten
        @list = line[4..7].map{|item| @gogi.select{|gogi| gogi.text == item }.first }
      else
        @example = Example.create :text => line.at(2)
        line[4..7].each_with_index{|flag,index| @list[index].examples << @example unless (flag.blank? || @list[index].blank?) }
      end
    end
  end
end

task :register_gogi_in_example => [:register_midashi_in_example] do
  Dir::glob(File.expand_path(dir_path)+'/**/*.csv').each do |source_file|
    CSV.foreach(source_file) do |line|
      if line.at(0).match(Regexp.new('^\d*$')).blank?
        next if line[1..-3].all?{|item| item.blank? }
        @gogi = Acceptation.create line[4..7].compact.map{|item| {:text => item}}
        targets = line.at(0).split(Regexp.new('\s'))
        DirectionWord.
          find(:all,:conditions => ["text IN (#{['?'] * targets.size * ','})"] + targets ).
          each{|item|item.acceptations << @gogi}
      end
    end
  end
end

task :register_midashi_in_example do
  set = Set.new
  Dir::glob(File.expand_path(dir_path)+'/**/*.csv').each do |source_file|
    CSV.foreach(source_file) do |line|
      if line.at(0).match(Regexp.new('^\d*$')).blank?
        next if line[1..-3].all?{|item| item.blank? }       
        line.at(0).split(Regexp.new('\s')).each{|item| set << item}
      end
    end
  end
  DirectionWord.create set.map{|item| {:text => item}}
end